from api.models import User, Role, RelationUserRole
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.csrf import csrf_exempt
import json
import time
from Crypto.Cipher import AES
from uniforms.response import Response
import base64


def get_user_level(user_id):
    role_ids = RelationUserRole.objects.filter(user_id=user_id).values_list("role_id")
    role_ids = list(role_ids)  # 获取当前用户所拥有角色id
    level = 0x7FFFFFFF  # 要获取最小的level 预先设为MAX_INT
    # 获取最小的角色level
    for role_id in role_ids:
        role_level = Role.objects.filter(id=role_id[0]).first().level
        level = min(level, role_level)
    return level


@csrf_exempt
@require_GET
def query_role_list(request):
    """
    获取用户可修改角色列表，获取大于当前用户最高角色等级(>=level)对应的角色列表
    params:
        params1: request
    method:
        method1: get
    return:
        {{
        level: 1,
        name: '管理员',
        code: 'admin',
        desc: '可管理除管理员外其他角色权限',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        authorityListDict: {
        Fault-injection: literal[true, false], // 故障注入授权
        DataMonitor: literal[true, false],  // 运维数据监控授权
        Detection: literal[true, false], // 故障检测授权
        Diagnosis: literal[true, false], // 故障诊断授权
        Manage: literal[true, false], // 用户管理
        RecordShow: literal[true, false] // 系统日志}
        },...}
    """
    try:
        user_id = request.user.id  # 获取当前用户的id
        level = get_user_level(user_id)  # 获取当前用户最高角色等级
        roles = Role.objects.filter(level__gte=level).all()  # 获取所有的结果
        res = []
        for role in roles:
            res.append(
                {
                    "level": role.level,
                    "name": role.name,
                    "code": role.code,
                    "desc": role.description,
                    "createTime": str(role.create_time.replace(tzinfo=None)),
                    "lastEditTime": str(role.last_edit_time.replace(tzinfo=None)),
                    "authorityListDict": {
                        "Fault-injection": role.fault_injection,
                        "DataMonitor": role.data_monitor,
                        "Detection": role.detection,
                        "Diagnosis": role.diagnosis,
                        "Manage": role.manage,
                        "RecordShow": role.RecordShow,
                    },
                }
            )
        return Response.success(data=res)
    except Exception as e:
        return Response.server_error(f"error:{str(e)}")


@csrf_exempt
@require_POST
def add_role(request):
    """
    添加角色,该角色等级为当前用户最高角色的等级+1
    params:
        params1: request
        {
        level: -1, // 需要后端修改重新赋值level
        name: '管理员',
        code: 'admin', // 不可重名
        desc: '可管理除管理员外其他角色权限',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        authorityListDict: {
            Fault-injection: [true,false], // 故障注入授权
            DataMonitor: [true,false], // 运维数据监控授权
            Detection: [true,false], // 故障检测授权
            Diagnosis: [true,false], // 故障诊断授权
            Manage: [true,false], // 用户管理
            RecordShow: [true,false] // 系统日志 }
        }
    method:
        method1: post
    return:
        { msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        user_id = request.user.id  # 获取当前用户的id
        level = get_user_level(user_id)  # 获取当前用户最高角色等级
        if level == 0x7FFFFFFF:
            return Response.bad_request("Not permitted to add role!")
        data["createTime"] = time.localtime(
            int(str(data["createTime"])[:-3])
        )  # 转换成localtime
        data["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["createTime"])
        data["lastEditTime"] = time.localtime(
            int(str(data["lastEditTime"])[:-3])
        )  # 转换成localtime
        data["lastEditTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["lastEditTime"])
        data["level"] = level + 1
        if Role.objects.filter(code=data["code"]).exists():
            return Response.bad_request("Role Already Exists!")
        else:
            Role.objects.create(
                level=data["level"],
                name=data["name"],
                code=data["code"],
                description=data["desc"],
                create_time=data["createTime"],
                last_edit_time=data["lastEditTime"],
                fault_injection=data["authorityListDict"]["Fault-injection"],
                data_monitor=data["authorityListDict"]["DataMonitor"],
                detection=data["authorityListDict"]["Detection"],
                diagnosis=data["authorityListDict"]["Diagnosis"],
                manage=data["authorityListDict"]["Manage"],
                RecordShow=data["authorityListDict"]["RecordShow"],
            )
            return Response.success()
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_http_methods(["PUT"])
def modify_role_auth(request):
    """
    修改角色权限
    params:
        params1: request
        {
        level: -1,
        name: '管理员',
        code: 'admin', // 不可重名
        desc: '可管理除管理员外其他角色权限',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        authorityListDict: {
            Fault-injection: [true,false], // 故障注入授权
            DataMonitor: [true,false], // 运维数据监控授权
            Detection: [true,false], // 故障检测授权
            Diagnosis: [true,false], // 故障诊断授权
            Manage: [true,false], // 用户管理
            RecordShow: [true,false],} // 系统日志
        }
    method:
        method1: put
    return:
        { msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        code = data["code"]
        if Role.objects.filter(code=code).exists():
            role = Role.objects.filter(code=code).first()
            role.name = data["name"]
            role.description = data["desc"]
            role.fault_injection = data["authorityListDict"]["Fault-injection"]
            role.data_monitor = data["authorityListDict"]["DataMonitor"]
            role.detection = data["authorityListDict"]["Detection"]
            role.diagnosis = data["authorityListDict"]["Diagnosis"]
            role.manage = data["authorityListDict"]["Manage"]
            role.RecordShow = data["authorityListDict"]["RecordShow"]
            role.save()
            return Response.success()
        else:
            return Response.bad_request("Role Not Exists!")
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_http_methods(["DELETE"])
def delete_role(request):
    """
    删除角色
    params:
        params1: request
        {
        level: 1,
        name: '管理员',
        code: 'admin',
        desc: '可管理除管理员外其他角色权限',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        authorityListDict: {
            Fault-injection: [true,false], // 故障注入授权
            DataMonitor: [true,false], // 运维数据监控授权
            Detection: [true,false], // 故障检测授权
            Diagnosis: [true,false], // 故障诊断授权
            Manage: [true,false], // 用户管理
            RecordShow: [true,false] // 系统日志
            }
        }
    method:
        method1: delete
    return:
        { msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        code = data["code"]
        if Role.objects.filter(code=code).exists():
            Role.objects.filter(code=code).delete()
            return Response.success()
        else:
            return Response.bad_request("Role Not Exists!")

    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_GET
def query_auth_able_list(request):
    """
    获取当前用户所能授权（>level）的角色列表
    params:
        params1: request
    method:
        method1: get
    return:
        ['code1', 'code2']
    """
    try:
        user_id = request.user.id  # 获取当前用户的id
        level = get_user_level(user_id)  # 获取当前用户最高角色等级
        roles = Role.objects.filter(level__gt=level).all()  # 获取所有的结果
        res = []
        for role in roles:
            res.append(role.code)
        return Response.success(data=res)
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_GET
def query_user_authority(request):
    """
    获取用户当前拥有的权限
    params:
        param1: request
    method:
        method1: get
    return:
        {
        Fault-injection: [true,false], // 故障注入授权
        DataMonitor: [true,false], // 运维数据监控授权
        Detection: [true,false], // 故障检测授权
        Diagnosis: [true,false], // 故障诊断授权
        Manage: [true,false], // 用户管理
        RecordShow: [true,false] // 系统日志
        }
    """
    try:
        # raise Exception("An error occurred")
        user = request.user
        role_ids = RelationUserRole.objects.filter(user_id=user.id).values_list(
            "role_id"
        )
        role_ids = list(role_ids)  # 获取当前用户所拥有角色id
        res = {
            "Fault-injection": False,
            "DataMonitor": False,
            "Detection": False,
            "Diagnosis": False,
            "Manage": False,
            "RecordShow": False,
        }
        for role_id in role_ids:
            role = Role.objects.filter(id=role_id[0]).get()
            if role.fault_injection:
                res["Fault-injection"] = True
            if role.data_monitor:
                res["DataMonitor"] = True
            if role.detection:
                res["Detection"] = True
            if role.diagnosis:
                res["Diagnosis"] = True
            if role.manage:
                res["Manage"] = True
            if role.RecordShow:
                res["RecordShow"] = True
        return Response.success(data=res)
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_GET
def query_user_list(request):
    """
    获取比当前用户最高角色等级高(>level)的用户列表
    params：
        param1： request
    method：
        method1： get
    return:
        [{
            id: 0,
            name: '张三',
            phone: '13478414545',
            email: 'zhangsan444@gamil.com',
            department: '管理部门',
            createTime: timestamp(11位), // 需要去除后三位
            lastEditTime: timestamp(11位), // 需要去除后三位
            description: ''
            ownRoles: ['user']
        },{},...]
    """
    try:
        user_id = request.user.id  # 获取当前用户的id
        level = get_user_level(user_id)  # 获取当前用户最高角色等级
        users = User.objects.all()
        new_users = []
        for user in users:
            if get_user_level(user.id) > level:
                new_users.append(user)
        res = []
        for new_user in new_users:
            own_roles = []
            role_ids = RelationUserRole.objects.filter(user_id=new_user.id).values_list(
                "role_id"
            )
            for role_id in role_ids:
                role = Role.objects.filter(id=role_id[0]).first()
                code = role.code
                own_roles.append(code)
            res.append(
                {
                    "id": new_user.id,
                    "name": new_user.username,
                    "phone": new_user.phone,
                    "email": new_user.email,
                    "password": new_user.password,
                    "department": new_user.department,
                    "createTime": str(new_user.create_time.replace(tzinfo=None)),
                    "lastEditTime": str(new_user.last_edit_time.replace(tzinfo=None)),
                    "description": new_user.description,
                    "ownRoles": own_roles,
                }
            )
        return Response.success(data=res)
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_POST
def add_user(request):
    """
    添加·对应用户
    params：
        param1： request
        {
        id: 0,
        name: '张三',
        phone: '13478414545',
        email: '',
        password: '',
        department: '管理部门',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        description: '',
        ownRoles: ['user']
        }
    method：
        method1： post
    return：
        {msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        decoder = AES.new("nkcs@@@@aiops@!3".encode(), mode=AES.MODE_ECB)
        data["password"] = (
            decoder.decrypt(base64.b64decode(data["password"])).decode().rstrip("\x00")
        )
        data["createTime"] = time.localtime(
            int(str(data["createTime"])[:-3])
        )  # 转换成localtime
        data["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["createTime"])
        data["lastEditTime"] = time.localtime(
            int(str(data["lastEditTime"])[:-3])
        )  # 转换成localtime
        data["lastEditTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["lastEditTime"])
        if User.objects.filter(username=data["name"]).exists():
            return Response.bad_request("Username Already Exists")
        user = User.objects.create(
            username=data["name"],
            password=data["password"],
            phone=data["phone"],
            email=data["email"],
            department=data["department"],
            description=data["description"],
            create_time=data["createTime"],
            last_edit_time=data["lastEditTime"],
        )

        for code in data["ownRoles"]:
            role = Role.objects.filter(code=code).first()
            if role is not None:
                RelationUserRole.objects.create(user_id=user.id, role_id=role.id)
        return Response.success()
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_http_methods(["PUT"])
def modify_user(request):
    """
    修改·对应用户
    params：
        param1： request
        {
        id: 0,
        name: '张三',
        phone: '13478414545',
        email: '',
        password: '',
        department: '管理部门',
        createTime: timestamp(11位), // 需要去除后三位
        lastEditTime: timestamp(11位), // 需要去除后三位
        description: '',
        ownRoles: ['user']
        }
    method：
        method1：put
    return：
        {msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        decoder = AES.new("nkcs@@@@aiops@!3".encode(), mode=AES.MODE_ECB)
        if data["password"] != "":
            data["password"] = (
                decoder.decrypt(base64.b64decode(data["password"]))
                .decode()
                .rstrip("\x00")
            )
        data["createTime"] = time.localtime(
            int(str(data["createTime"])[:-3])
        )  # 转换成localtime
        data["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["createTime"])
        data["lastEditTime"] = time.localtime(
            int(str(data["lastEditTime"])[:-3])
        )  # 转换成localtime
        data["lastEditTime"] = time.strftime("%Y-%m-%d %H:%M:%S", data["lastEditTime"])
        if not User.objects.filter(id=data["id"]).exists():
            return Response.bad_request("User Doesn't Exist")
        user = User.objects.filter(id=data["id"]).first()
        user.id = data["id"]
        user.username = data["name"]
        user.phone = data["phone"]
        user.email = data["email"]
        user.department = data["department"]
        user.description = data["description"]
        user.create_time = data["createTime"]
        user.last_edit_time = data["lastEditTime"]
        print(data)

        RelationUserRole.objects.filter(user_id=user.id).delete()
        for code in data["ownRoles"]:
            role = Role.objects.filter(code=code).first()
            if role is not None:
                RelationUserRole.objects.create(user_id=user.id, role_id=role.id)
        if data["password"] != "" and user.password != data["password"]:
            user.password = data["password"]
            user.save()
        else:
            user.save(reset_pw=False)
        return Response.success()
    except Exception as e:
        return Response.server_error(f"error: {e}")


@csrf_exempt
@require_http_methods(["DELETE"])
def delete_user(request):
    """
    删除·对应用户
    params:
        param1: request
        {id: string}
        {id: 0}
    method:
        method1: delete
    return:
        {msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        del_id = data["id"]
        if User.objects.filter(id=del_id).exists():
            User.objects.filter(id=del_id).delete()
            return Response.success()
        else:
            return Response.bad_request("User Not Exists!")
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")


@csrf_exempt
@require_http_methods(["DELETE"])
def delete_user_by_batch(request):
    """
    批量·删除·对应用户
    params:
        param1: request
        [Number]
        [0,1,2]
    method:
        method1: delete
    return:
        {msg: "success"}
    """
    try:
        raw_data = request.body  # 获取原始请求体数据
        data = json.loads(raw_data)  # 解析Json数据
        for del_id in data:
            if not User.objects.filter(id=del_id).exists():
                return Response.bad_request("User Not Exists!")
        for del_id in data:
            User.objects.filter(id=del_id).delete()
        return Response.success()
    except Exception as e:
        return Response.server_error(f"error: {str(e)}")
